#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
基本图形生成工具
使用 PySide6 创建图形生成界面
"""

import sys
from pathlib import Path
from typing import Optional, Tuple, List
from enum import Enum

from PySide6.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QGroupBox, QLabel, QComboBox, QSpinBox, QDoubleSpinBox,
    QPushButton, QColorDialog, QFileDialog, QMessageBox,
    QGridLayout, QSlider, QTabWidget, QTextEdit, QCheckBox
)
from PySide6.QtCore import Qt, Signal, QSize, QPointF, QRectF, QPoint
from PySide6.QtGui import (
    QPainter, QColor, QPen, QBrush, QPixmap, QFont, 
    QPainterPath, QPolygonF, QAction
)


class ShapeType(Enum):
    """图形类型枚举"""
    RECTANGLE = "矩形"
    CIRCLE = "圆形"
    TRIANGLE = "三角形"
    POLYGON = "多边形"
    ELLIPSE = "椭圆"
    STAR = "星形"
    HEART = "心形"
    LONG_RECTANGLE = "长方形"


class CanvasWidget(QWidget):
    """绘图画布组件"""
    
    shape_changed = Signal()
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setMinimumSize(400, 400)
        self.setStyleSheet("background-color: white; border: 1px solid black;")
        
        # 图形参数
        self.shape_type = ShapeType.RECTANGLE
        self.fill_color = QColor(100, 149, 237)  # 蓝色
        self.border_color = QColor(0, 0, 0)  # 黑色
        self.border_width = 2
        self.size = 100
        self.position = QPointF(200, 200)
        self.rotation = 0
        self.polygon_sides = 5
        self.star_points = 5
        self.show_border = True
        self.fill_shape = True
        
        # 额外参数
        self.ellipse_width = 150
        self.ellipse_height = 100
        self.long_rectangle_width = 200
        self.long_rectangle_height = 100
        self.corner_radius = 0  # 圆角半径，0表示尖角
        
    def paintEvent(self, event):
        """绘制事件"""
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        
        # 设置画笔（边框）
        if self.show_border:
            pen = QPen(self.border_color, self.border_width)
            painter.setPen(pen)
        else:
            # 如果不显示边框，设置透明画笔
            pen = QPen(Qt.transparent)
            painter.setPen(pen)
        
        # 设置画刷（填充）
        if self.fill_shape:
            brush = QBrush(self.fill_color)
            painter.setBrush(brush)
        else:
            # 如果不填充，设置透明画刷
            brush = QBrush(Qt.transparent)
            painter.setBrush(brush)
        
        # 保存当前状态
        painter.save()
        
        # 应用旋转
        painter.translate(self.position)
        painter.rotate(self.rotation)
        painter.translate(-self.position)
        
        # 根据图形类型绘制
        if self.shape_type == ShapeType.RECTANGLE:
            self._draw_rectangle(painter)
        elif self.shape_type == ShapeType.CIRCLE:
            self._draw_circle(painter)
        elif self.shape_type == ShapeType.TRIANGLE:
            self._draw_triangle(painter)
        elif self.shape_type == ShapeType.POLYGON:
            self._draw_polygon(painter)
        elif self.shape_type == ShapeType.ELLIPSE:
            self._draw_ellipse(painter)
        elif self.shape_type == ShapeType.STAR:
            self._draw_star(painter)
        elif self.shape_type == ShapeType.HEART:
            self._draw_heart(painter)
        elif self.shape_type == ShapeType.LONG_RECTANGLE:
            self._draw_long_rectangle(painter)
        
        # 恢复状态
        painter.restore()
    
    def _draw_rectangle(self, painter):
        """绘制矩形"""
        rect = QRectF(
            self.position.x() - self.size/2,
            self.position.y() - self.size/2,
            self.size,
            self.size
        )
        if self.corner_radius > 0:
            # 绘制圆角矩形
            painter.drawRoundedRect(rect, self.corner_radius, self.corner_radius)
        else:
            # 绘制普通矩形
            painter.drawRect(rect)
    
    def _draw_circle(self, painter):
        """绘制圆形"""
        rect = QRectF(
            self.position.x() - self.size/2,
            self.position.y() - self.size/2,
            self.size,
            self.size
        )
        painter.drawEllipse(rect)
    
    def _draw_triangle(self, painter):
        """绘制三角形"""
        import math
        height = self.size * 0.866  # 等边三角形高度
        points = [
            QPointF(self.position.x(), self.position.y() - height/2),
            QPointF(self.position.x() - self.size/2, self.position.y() + height/2),
            QPointF(self.position.x() + self.size/2, self.position.y() + height/2)
        ]
        
        if self.corner_radius > 0:
            # 使用 QPainterPath 绘制圆角三角形
            path = QPainterPath()
            
            # 计算边长
            edge_length = self.size
            
            # 限制圆角半径
            max_radius = edge_length / 3
            radius = min(self.corner_radius, max_radius)
            
            # 计算每个顶点的圆角
            for i in range(3):
                current = points[i]
                prev_point = points[(i - 1) % 3]
                next_point = points[(i + 1) % 3]
                
                # 计算两条边的向量
                v1 = prev_point - current
                v2 = next_point - current
                
                # 计算边的长度
                len1 = math.sqrt(v1.x()**2 + v1.y()**2)
                len2 = math.sqrt(v2.x()**2 + v2.y()**2)
                
                if len1 > 0 and len2 > 0:
                    # 归一化向量
                    v1 = v1 / len1
                    v2 = v2 / len2
                    
                    # 计算圆角的起点和终点
                    start = current + v1 * radius
                    end = current + v2 * radius
                    
                    if i == 0:
                        path.moveTo(start)
                    else:
                        path.lineTo(start)
                    
                    # 绘制圆角
                    path.quadTo(current, end)
            
            path.closeSubpath()
            painter.drawPath(path)
        else:
            # 绘制普通三角形
            triangle = QPolygonF(points)
            painter.drawPolygon(triangle)
    
    def _draw_polygon(self, painter):
        """绘制多边形"""
        import math
        points = []
        angle_step = 360 / self.polygon_sides
        for i in range(self.polygon_sides):
            angle = i * angle_step - 90  # 从顶部开始
            x = self.position.x() + self.size/2 * math.cos(math.radians(angle))
            y = self.position.y() + self.size/2 * math.sin(math.radians(angle))
            points.append(QPointF(x, y))
        
        if self.corner_radius > 0 and self.polygon_sides >= 3:
            # 使用 QPainterPath 绘制圆角多边形
            path = QPainterPath()
            
            # 计算边长
            edge_length = self.size * math.sin(math.pi / self.polygon_sides)
            
            # 限制圆角半径
            max_radius = edge_length / 2
            radius = min(self.corner_radius, max_radius)
            
            # 计算每个顶点的圆角
            for i in range(self.polygon_sides):
                current = points[i]
                prev_point = points[(i - 1) % self.polygon_sides]
                next_point = points[(i + 1) % self.polygon_sides]
                
                # 计算两条边的向量
                v1 = prev_point - current
                v2 = next_point - current
                
                # 计算边的长度
                len1 = math.sqrt(v1.x()**2 + v1.y()**2)
                len2 = math.sqrt(v2.x()**2 + v2.y()**2)
                
                if len1 > 0 and len2 > 0:
                    # 归一化向量
                    v1 = v1 / len1
                    v2 = v2 / len2
                    
                    # 计算圆角的起点和终点
                    start = current + v1 * radius
                    end = current + v2 * radius
                    
                    if i == 0:
                        path.moveTo(start)
                    else:
                        path.lineTo(start)
                    
                    # 绘制圆角
                    path.quadTo(current, end)
            
            path.closeSubpath()
            painter.drawPath(path)
        else:
            # 绘制普通多边形
            polygon = QPolygonF(points)
            painter.drawPolygon(polygon)
    
    def _draw_long_rectangle(self, painter):
        """绘制长方形"""
        rect = QRectF(
            self.position.x() - self.long_rectangle_width/2,
            self.position.y() - self.long_rectangle_height/2,
            self.long_rectangle_width,
            self.long_rectangle_height
        )
        if self.corner_radius > 0:
            # 绘制圆角长方形
            painter.drawRoundedRect(rect, self.corner_radius, self.corner_radius)
        else:
            # 绘制普通长方形
            painter.drawRect(rect)
    
    def _draw_ellipse(self, painter):
        """绘制椭圆"""
        rect = QRectF(
            self.position.x() - self.ellipse_width/2,
            self.position.y() - self.ellipse_height/2,
            self.ellipse_width,
            self.ellipse_height
        )
        painter.drawEllipse(rect)
    
    def _draw_star(self, painter):
        """绘制星形"""
        import math
        points = []
        outer_radius = self.size / 2
        inner_radius = outer_radius * 0.4
        
        for i in range(self.star_points * 2):
            angle = i * 180 / self.star_points - 90
            radius = outer_radius if i % 2 == 0 else inner_radius
            x = self.position.x() + radius * math.cos(math.radians(angle))
            y = self.position.y() + radius * math.sin(math.radians(angle))
            points.append(QPointF(x, y))
        
        star = QPolygonF(points)
        painter.drawPolygon(star)
    
    def _draw_heart(self, painter):
        """绘制心形"""
        path = QPainterPath()
        size = self.size / 2
        
        # 使用贝塞尔曲线绘制心形
        path.moveTo(self.position.x(), self.position.y() + size * 0.3)
        
        # 左半部分
        path.cubicTo(
            self.position.x() - size * 0.5, self.position.y() - size * 0.3,
            self.position.x() - size, self.position.y() + size * 0.1,
            self.position.x(), self.position.y() + size
        )
        
        # 右半部分
        path.cubicTo(
            self.position.x() + size, self.position.y() + size * 0.1,
            self.position.x() + size * 0.5, self.position.y() - size * 0.3,
            self.position.x(), self.position.y() + size * 0.3
        )
        
        painter.drawPath(path)
    
    def get_shape_bounds(self):
        """获取图形的边界矩形"""
        import math
        
        # 根据图形类型计算边界
        if self.shape_type == ShapeType.RECTANGLE:
            return QRectF(
                self.position.x() - self.size/2,
                self.position.y() - self.size/2,
                self.size,
                self.size
            )
        elif self.shape_type == ShapeType.CIRCLE:
            return QRectF(
                self.position.x() - self.size/2,
                self.position.y() - self.size/2,
                self.size,
                self.size
            )
        elif self.shape_type == ShapeType.TRIANGLE:
            height = self.size * 0.866  # 等边三角形高度
            return QRectF(
                self.position.x() - self.size/2,
                self.position.y() - height/2,
                self.size,
                height
            )
        elif self.shape_type == ShapeType.POLYGON:
            # 多边形边界
            radius = self.size / 2
            return QRectF(
                self.position.x() - radius,
                self.position.y() - radius,
                radius * 2,
                radius * 2
            )
        elif self.shape_type == ShapeType.ELLIPSE:
            return QRectF(
                self.position.x() - self.ellipse_width/2,
                self.position.y() - self.ellipse_height/2,
                self.ellipse_width,
                self.ellipse_height
            )
        elif self.shape_type == ShapeType.STAR:
            # 星形边界
            outer_radius = self.size / 2
            return QRectF(
                self.position.x() - outer_radius,
                self.position.y() - outer_radius,
                outer_radius * 2,
                outer_radius * 2
            )
        elif self.shape_type == ShapeType.HEART:
            # 心形边界
            size = self.size / 2
            return QRectF(
                self.position.x() - size,
                self.position.y() - size * 0.7,
                size * 2,
                size * 1.7
            )
        elif self.shape_type == ShapeType.LONG_RECTANGLE:
            return QRectF(
                self.position.x() - self.long_rectangle_width/2,
                self.position.y() - self.long_rectangle_height/2,
                self.long_rectangle_width,
                self.long_rectangle_height
            )
        
        return None
    
    def update_shape(self):
        """更新图形"""
        self.update()
        self.shape_changed.emit()


class ShapeGeneratorWindow(QMainWindow):
    """图形生成器主窗口"""
    
    def __init__(self):
        super().__init__()
        self.setWindowTitle("基本图形生成工具")
        self.setGeometry(100, 100, 800, 600)
        
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QHBoxLayout(central_widget)
        
        # 创建画布（必须在控制面板之前创建）
        self.canvas = CanvasWidget()
        self.canvas.shape_changed.connect(self.on_shape_changed)
        main_layout.addWidget(self.canvas, 2)
        
        # 创建控制面板
        self.control_panel = self._create_control_panel()
        main_layout.addWidget(self.control_panel, 1)
        
        # 创建菜单栏
        self._create_menu_bar()
        
        # 创建状态栏
        self.statusBar().showMessage("就绪")
    
    def _create_menu_bar(self):
        """创建菜单栏"""
        menubar = self.menuBar()
        
        # 文件菜单
        file_menu = menubar.addMenu("文件")
        
        save_action = QAction("保存图像", self)
        save_action.setShortcut("Ctrl+S")
        save_action.triggered.connect(self.save_image)
        file_menu.addAction(save_action)
        
        file_menu.addSeparator()
        
        exit_action = QAction("退出", self)
        exit_action.setShortcut("Ctrl+Q")
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)
        
        # 帮助菜单
        help_menu = menubar.addMenu("帮助")
        
        about_action = QAction("关于", self)
        about_action.triggered.connect(self.show_about)
        help_menu.addAction(about_action)
    
    def _create_control_panel(self):
        """创建控制面板"""
        panel = QWidget()
        layout = QVBoxLayout(panel)
        
        # 创建主水平布局，分成左右两列
        main_layout = QHBoxLayout()
        layout.addLayout(main_layout)
        
        # 左列布局
        left_column = QVBoxLayout()
        main_layout.addLayout(left_column)
        
        # 右列布局
        right_column = QVBoxLayout()
        main_layout.addLayout(right_column)
        
        # ===== 左列内容 =====
        
        # 图形类型选择
        shape_group = QGroupBox("图形类型")
        shape_layout = QHBoxLayout(shape_group)
        
        self.shape_combo = QComboBox()
        for shape in ShapeType:
            self.shape_combo.addItem(shape.value, shape)
        self.shape_combo.currentIndexChanged.connect(self.on_shape_type_changed)
        shape_layout.addWidget(self.shape_combo)
        
        left_column.addWidget(shape_group)
        
        # 大小控制
        size_group = QGroupBox("大小")
        size_layout = QHBoxLayout(size_group)
        
        size_layout.addWidget(QLabel("尺寸:"))
        self.size_spin = QSpinBox()
        self.size_spin.setRange(10, 500)
        self.size_spin.setValue(100)
        self.size_spin.valueChanged.connect(self.on_size_changed)
        size_layout.addWidget(self.size_spin)
        
        left_column.addWidget(size_group)
        
        # 旋转控制
        rotation_group = QGroupBox("旋转")
        rotation_layout = QHBoxLayout(rotation_group)
        
        rotation_layout.addWidget(QLabel("角度:"))
        self.rotation_slider = QSlider(Qt.Horizontal)
        self.rotation_slider.setRange(0, 360)
        self.rotation_slider.valueChanged.connect(self.on_rotation_changed)
        rotation_layout.addWidget(self.rotation_slider)
        
        self.rotation_label = QLabel("0°")
        rotation_layout.addWidget(self.rotation_label)
        
        left_column.addWidget(rotation_group)
        
        # 圆角控制
        corner_group = QGroupBox("圆角")
        corner_layout = QHBoxLayout(corner_group)
        
        corner_layout.addWidget(QLabel("圆角半径:"))
        self.corner_radius_spin = QSpinBox()
        self.corner_radius_spin.setRange(0, 50)
        self.corner_radius_spin.setValue(0)
        self.corner_radius_spin.valueChanged.connect(self.on_corner_radius_changed)
        corner_layout.addWidget(self.corner_radius_spin)
        
        left_column.addWidget(corner_group)
        
        # ===== 右列内容 =====
        
        # 填充颜色
        fill_group = QGroupBox("填充颜色")
        fill_layout = QVBoxLayout(fill_group)
        
        fill_row1 = QHBoxLayout()
        self.fill_color_btn = QPushButton("选择填充颜色")
        self.fill_color_btn.clicked.connect(self.choose_fill_color)
        fill_row1.addWidget(self.fill_color_btn)
        
        self.fill_color_label = QLabel()
        self.fill_color_label.setFixedSize(50, 20)
        self.fill_color_label.setStyleSheet(f"background-color: {self.canvas.fill_color.name()};")
        fill_row1.addWidget(self.fill_color_label)
        fill_layout.addLayout(fill_row1)
        
        self.fill_checkbox = QCheckBox("启用填充")
        self.fill_checkbox.setChecked(True)
        self.fill_checkbox.toggled.connect(self.on_fill_toggled)
        fill_layout.addWidget(self.fill_checkbox)
        
        right_column.addWidget(fill_group)
        
        # 边框颜色
        border_group = QGroupBox("边框设置")
        border_layout = QGridLayout(border_group)
        
        border_color_row = QHBoxLayout()
        self.border_color_btn = QPushButton("选择边框颜色")
        self.border_color_btn.clicked.connect(self.choose_border_color)
        border_color_row.addWidget(self.border_color_btn)
        
        self.border_color_label = QLabel()
        self.border_color_label.setFixedSize(50, 20)
        self.border_color_label.setStyleSheet(f"background-color: {self.canvas.border_color.name()};")
        border_color_row.addWidget(self.border_color_label)
        border_layout.addLayout(border_color_row, 0, 0, 1, 2)
        
        border_layout.addWidget(QLabel("宽度:"), 1, 0)
        self.border_width_spin = QSpinBox()
        self.border_width_spin.setRange(1, 20)
        self.border_width_spin.setValue(2)
        self.border_width_spin.valueChanged.connect(self.on_border_width_changed)
        border_layout.addWidget(self.border_width_spin, 1, 1)
        
        self.border_checkbox = QCheckBox("显示边框")
        self.border_checkbox.setChecked(True)
        self.border_checkbox.toggled.connect(self.on_border_toggled)
        border_layout.addWidget(self.border_checkbox, 2, 0, 1, 2)
        
        right_column.addWidget(border_group)
        
        # 高级设置组合框
        advanced_group = QGroupBox("高级设置")
        advanced_layout = QVBoxLayout(advanced_group)
        
        # 多边形设置
        polygon_layout = QHBoxLayout()
        polygon_layout.addWidget(QLabel("多边形边数:"))
        self.polygon_sides_spin = QSpinBox()
        self.polygon_sides_spin.setRange(3, 20)
        self.polygon_sides_spin.setValue(5)
        self.polygon_sides_spin.valueChanged.connect(self.on_polygon_sides_changed)
        polygon_layout.addWidget(self.polygon_sides_spin)
        advanced_layout.addLayout(polygon_layout)
        
        # 星形设置
        star_layout = QHBoxLayout()
        star_layout.addWidget(QLabel("星形角数:"))
        self.star_points_spin = QSpinBox()
        self.star_points_spin.setRange(3, 20)
        self.star_points_spin.setValue(5)
        self.star_points_spin.valueChanged.connect(self.on_star_points_changed)
        star_layout.addWidget(self.star_points_spin)
        advanced_layout.addLayout(star_layout)
        
        # 椭圆设置
        ellipse_layout = QHBoxLayout()
        ellipse_layout.addWidget(QLabel("椭圆宽:"))
        self.ellipse_width_spin = QSpinBox()
        self.ellipse_width_spin.setRange(20, 400)
        self.ellipse_width_spin.setValue(150)
        self.ellipse_width_spin.valueChanged.connect(self.on_ellipse_size_changed)
        ellipse_layout.addWidget(self.ellipse_width_spin)
        advanced_layout.addLayout(ellipse_layout)
        
        ellipse_height_layout = QHBoxLayout()
        ellipse_height_layout.addWidget(QLabel("椭圆高:"))
        self.ellipse_height_spin = QSpinBox()
        self.ellipse_height_spin.setRange(20, 400)
        self.ellipse_height_spin.setValue(100)
        self.ellipse_height_spin.valueChanged.connect(self.on_ellipse_size_changed)
        ellipse_height_layout.addWidget(self.ellipse_height_spin)
        advanced_layout.addLayout(ellipse_height_layout)
        
        # 长方形设置
        long_rect_width_layout = QHBoxLayout()
        long_rect_width_layout.addWidget(QLabel("长方形宽:"))
        self.long_rect_width_spin = QSpinBox()
        self.long_rect_width_spin.setRange(20, 400)
        self.long_rect_width_spin.setValue(200)
        self.long_rect_width_spin.valueChanged.connect(self.on_long_rectangle_size_changed)
        long_rect_width_layout.addWidget(self.long_rect_width_spin)
        advanced_layout.addLayout(long_rect_width_layout)
        
        long_rect_height_layout = QHBoxLayout()
        long_rect_height_layout.addWidget(QLabel("长方形高:"))
        self.long_rect_height_spin = QSpinBox()
        self.long_rect_height_spin.setRange(20, 400)
        self.long_rect_height_spin.setValue(100)
        self.long_rect_height_spin.valueChanged.connect(self.on_long_rectangle_size_changed)
        long_rect_height_layout.addWidget(self.long_rect_height_spin)
        advanced_layout.addLayout(long_rect_height_layout)
        
        right_column.addWidget(advanced_group)
        
        # 导出设置组合框
        export_group = QGroupBox("导出设置")
        export_layout = QGridLayout(export_group)
        
        # 留白设置
        export_layout.addWidget(QLabel("上留白:"), 0, 0)
        self.padding_top_spin = QSpinBox()
        self.padding_top_spin.setRange(0, 100)
        self.padding_top_spin.setValue(10)
        export_layout.addWidget(self.padding_top_spin, 0, 1)
        
        export_layout.addWidget(QLabel("下留白:"), 0, 2)
        self.padding_bottom_spin = QSpinBox()
        self.padding_bottom_spin.setRange(0, 100)
        self.padding_bottom_spin.setValue(10)
        export_layout.addWidget(self.padding_bottom_spin, 0, 3)
        
        export_layout.addWidget(QLabel("左留白:"), 1, 0)
        self.padding_left_spin = QSpinBox()
        self.padding_left_spin.setRange(0, 100)
        self.padding_left_spin.setValue(10)
        export_layout.addWidget(self.padding_left_spin, 1, 1)
        
        export_layout.addWidget(QLabel("右留白:"), 1, 2)
        self.padding_right_spin = QSpinBox()
        self.padding_right_spin.setRange(0, 100)
        self.padding_right_spin.setValue(10)
        export_layout.addWidget(self.padding_right_spin, 1, 3)
        
        # 透明背景选项
        self.transparent_bg_checkbox = QCheckBox("透明背景")
        self.transparent_bg_checkbox.setChecked(True)
        export_layout.addWidget(self.transparent_bg_checkbox, 2, 0, 1, 2)
        
        # 自动裁剪选项
        self.auto_crop_checkbox = QCheckBox("自动裁剪到图形大小")
        self.auto_crop_checkbox.setChecked(True)
        export_layout.addWidget(self.auto_crop_checkbox, 2, 2, 1, 2)
        
        right_column.addWidget(export_group)
        
        # 操作按钮
        button_layout = QHBoxLayout()
        
        refresh_btn = QPushButton("刷新画布")
        refresh_btn.clicked.connect(self.canvas.update_shape)
        button_layout.addWidget(refresh_btn)
        
        save_btn = QPushButton("保存图像")
        save_btn.clicked.connect(self.save_image)
        button_layout.addWidget(save_btn)
        
        layout.addLayout(button_layout)
        layout.addStretch()
        
        return panel
    
    def on_shape_type_changed(self, index):
        """图形类型改变事件"""
        self.canvas.shape_type = self.shape_combo.itemData(index)
        self.canvas.update_shape()
        self.statusBar().showMessage(f"已选择: {self.shape_combo.itemText(index)}")
    
    
    def on_size_changed(self):
        """大小改变事件"""
        self.canvas.size = self.size_spin.value()
        self.canvas.update_shape()
    
    def on_rotation_changed(self, value):
        """旋转改变事件"""
        self.canvas.rotation = value
        self.rotation_label.setText(f"{value}°")
        self.canvas.update_shape()
    
    def on_fill_toggled(self, checked):
        """填充切换事件"""
        self.canvas.fill_shape = checked
        self.canvas.update_shape()
    
    def on_border_toggled(self, checked):
        """边框切换事件"""
        self.canvas.show_border = checked
        self.canvas.update_shape()
    
    def on_border_width_changed(self, value):
        """边框宽度改变事件"""
        self.canvas.border_width = value
        # 无论边框是否显示，都更新画布以确保宽度设置生效
        self.canvas.update_shape()
    
    def on_polygon_sides_changed(self, value):
        """多边形边数改变事件"""
        self.canvas.polygon_sides = value
        if self.canvas.shape_type == ShapeType.POLYGON:
            self.canvas.update_shape()
    
    def on_star_points_changed(self, value):
        """星形角数改变事件"""
        self.canvas.star_points = value
        if self.canvas.shape_type == ShapeType.STAR:
            self.canvas.update_shape()
    
    def on_ellipse_size_changed(self):
        """椭圆尺寸改变事件"""
        self.canvas.ellipse_width = self.ellipse_width_spin.value()
        self.canvas.ellipse_height = self.ellipse_height_spin.value()
        if self.canvas.shape_type == ShapeType.ELLIPSE:
            self.canvas.update_shape()
    
    def on_long_rectangle_size_changed(self):
        """长方形尺寸改变事件"""
        self.canvas.long_rectangle_width = self.long_rect_width_spin.value()
        self.canvas.long_rectangle_height = self.long_rect_height_spin.value()
        if self.canvas.shape_type == ShapeType.LONG_RECTANGLE:
            self.canvas.update_shape()
    
    def on_corner_radius_changed(self, value):
        """圆角半径改变事件"""
        self.canvas.corner_radius = value
        # 对于支持圆角的图形，立即更新画布
        if self.canvas.shape_type in [ShapeType.RECTANGLE, ShapeType.LONG_RECTANGLE, ShapeType.TRIANGLE, ShapeType.POLYGON]:
            self.canvas.update_shape()
    
    def choose_fill_color(self):
        """选择填充颜色"""
        color = QColorDialog.getColor(self.canvas.fill_color, self, "选择填充颜色")
        if color.isValid():
            self.canvas.fill_color = color
            self.fill_color_label.setStyleSheet(f"background-color: {color.name()};")
            self.canvas.update_shape()
    
    def choose_border_color(self):
        """选择边框颜色"""
        color = QColorDialog.getColor(self.canvas.border_color, self, "选择边框颜色")
        if color.isValid():
            self.canvas.border_color = color
            self.border_color_label.setStyleSheet(f"background-color: {color.name()};")
            # 无论边框是否显示，都更新画布以确保颜色设置生效
            self.canvas.update_shape()
    
    def on_shape_changed(self):
        """图形改变事件"""
        pass
    
    def save_image(self):
        """保存图像"""
        file_path, _ = QFileDialog.getSaveFileName(
            self, "保存图像", "", "PNG 图像 (*.png);;所有文件 (*)"
        )
        
        if file_path:
            # 确保文件名以.png结尾
            if not file_path.lower().endswith('.png'):
                file_path += '.png'
                
            # 获取留白设置
            padding_top = self.padding_top_spin.value()
            padding_bottom = self.padding_bottom_spin.value()
            padding_left = self.padding_left_spin.value()
            padding_right = self.padding_right_spin.value()
            
            # 获取导出选项
            transparent_bg = self.transparent_bg_checkbox.isChecked()
            auto_crop = self.auto_crop_checkbox.isChecked()
            
            if auto_crop:
                # 自动裁剪模式
                # 计算图形的实际边界
                shape_bounds = self.canvas.get_shape_bounds()
                
                if shape_bounds:
                    # 计算裁剪后的尺寸
                    crop_width = shape_bounds.width() + padding_left + padding_right
                    crop_height = shape_bounds.height() + padding_top + padding_bottom
                    
                    # 确保最小尺寸
                    crop_width = max(crop_width, 10)
                    crop_height = max(crop_height, 10)
                    
                    # 创建一个与裁剪后尺寸同样大小的图片，支持透明通道
                    pixmap = QPixmap(int(crop_width), int(crop_height))
                    
                    # 设置背景
                    if transparent_bg:
                        pixmap.fill(QColor(0, 0, 0, 0))  # 透明背景
                    else:
                        pixmap.fill(Qt.white)  # 白色背景
                    
                    # 创建 painter 并直接绘制图形
                    painter = QPainter(pixmap)
                    painter.setRenderHint(QPainter.Antialiasing)
                    
                    # 计算偏移量，使图形居中并加上留白
                    offset_x = padding_left - shape_bounds.left()
                    offset_y = padding_top - shape_bounds.top()
                    
                    # 平移 painter 以实现偏移
                    painter.translate(offset_x, offset_y)
                    
                    # 直接绘制图形，而不是渲染整个画布
                    self._draw_shape_directly(painter)
                    painter.end()
                else:
                    # 如果没有图形边界，使用整个画布
                    canvas_size = self.canvas.size()
                    pixmap = QPixmap(canvas_size)
                    
                    if transparent_bg:
                        pixmap.fill(QColor(0, 0, 0, 0))  # 透明背景
                    else:
                        pixmap.fill(Qt.white)  # 白色背景
                    
                    painter = QPainter(pixmap)
                    painter.setRenderHint(QPainter.Antialiasing)
                    self._draw_shape_directly(painter)
                    painter.end()
            else:
                # 完整画布模式
                canvas_size = self.canvas.size()
                pixmap = QPixmap(canvas_size)
                
                if transparent_bg:
                    pixmap.fill(QColor(0, 0, 0, 0))  # 透明背景
                else:
                    pixmap.fill(Qt.white)  # 白色背景
                
                painter = QPainter(pixmap)
                painter.setRenderHint(QPainter.Antialiasing)
                self._draw_shape_directly(painter)
                painter.end()
            
            # 保存图像
            if pixmap.save(file_path, "PNG"):
                self.statusBar().showMessage(f"图像已保存: {file_path}")
                QMessageBox.information(self, "保存成功", f"图像已保存到:\n{file_path}")
            else:
                QMessageBox.critical(self, "保存失败", "无法保存图像")
    
    def _draw_shape_directly(self, painter):
        """直接绘制图形，不包含画布背景"""
        # 设置画笔（边框）
        if self.canvas.show_border:
            pen = QPen(self.canvas.border_color, self.canvas.border_width)
            painter.setPen(pen)
        else:
            # 如果不显示边框，设置透明画笔
            pen = QPen(Qt.transparent)
            painter.setPen(pen)
        
        # 设置画刷（填充）
        if self.canvas.fill_shape:
            brush = QBrush(self.canvas.fill_color)
            painter.setBrush(brush)
        else:
            # 如果不填充，设置透明画刷
            brush = QBrush(Qt.transparent)
            painter.setBrush(brush)
        
        # 保存当前状态
        painter.save()
        
        # 应用旋转
        painter.translate(self.canvas.position)
        painter.rotate(self.canvas.rotation)
        painter.translate(-self.canvas.position)
        
        # 根据图形类型绘制
        if self.canvas.shape_type == ShapeType.RECTANGLE:
            self.canvas._draw_rectangle(painter)
        elif self.canvas.shape_type == ShapeType.CIRCLE:
            self.canvas._draw_circle(painter)
        elif self.canvas.shape_type == ShapeType.TRIANGLE:
            self.canvas._draw_triangle(painter)
        elif self.canvas.shape_type == ShapeType.POLYGON:
            self.canvas._draw_polygon(painter)
        elif self.canvas.shape_type == ShapeType.ELLIPSE:
            self.canvas._draw_ellipse(painter)
        elif self.canvas.shape_type == ShapeType.STAR:
            self.canvas._draw_star(painter)
        elif self.canvas.shape_type == ShapeType.HEART:
            self.canvas._draw_heart(painter)
        elif self.canvas.shape_type == ShapeType.LONG_RECTANGLE:
            self.canvas._draw_long_rectangle(painter)
        
        # 恢复状态
        painter.restore()
    
    def show_about(self):
        """显示关于对话框"""
        QMessageBox.about(self, "关于", 
                         "基本图形生成工具\n\n"
                         "使用 PySide6 开发\n"
                         "支持多种基本图形的生成和编辑\n\n"
                         "版本: 1.0")


def main():
    """主函数"""
    app = QApplication(sys.argv)
    
    # 设置应用程序属性
    app.setApplicationName("基本图形生成工具")
    app.setApplicationVersion("1.0")
    
    # 创建并显示主窗口
    window = ShapeGeneratorWindow()
    window.show()
    
    sys.exit(app.exec())


if __name__ == "__main__":
    main()